<template>
  <el-dialog
      :model-value="roleDialogVisible"
      title="分配角色"
      width="30%"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        label-width="100px"
    >

      <el-checkbox-group v-model="form.checkedRoles">
        <el-checkbox v-for="role in form.roleList" :id="String(role.id)" :key="role.id" :value="role.id" name="checkedRoles">
          {{ role.name }}
        </el-checkbox>
      </el-checkbox-group>

    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>

import {defineEmits, defineProps, ref, watch} from "vue";
import requestUtil from "@/util/request";
import {ElMessage} from 'element-plus'


const props = defineProps(
    {
      id: {
        type: Number,
        default: -1,
        required: true
      },
      roleDialogVisible: {
        type: Boolean,
        default: false,
        required: true
      },
      sysRoleList: {
        type: Array,
        default: [],
        required: true
      }
    }
)

const form = ref({
  id: -1,
  roleList: [],
  checkedRoles: []
})


const formRef = ref(null)

const initFormData = async (id) => {
  try {
    const res = await requestUtil.get("system/role/");
    console.log("获取角色列表成功", res)
    form.value.roleList = res.results;
    form.value.id = id;
  } catch (err) {
    console.error("获取角色列表失败", err)
  }
}


watch(
    () => props.roleDialogVisible,
    (newVal) => {
      if (newVal) {
        let id = props.id;
        console.log("id:" + id)
        if (id != -1) {
          form.value.checkedRoles = []
          props.sysRoleList.forEach(item => {
            // console.log("=========item:" + JSON.stringify(item))
            // console.log("item.id:" + item.id)
            form.value.checkedRoles.push(item.id);
          })
          initFormData(id).catch(err => {
            console.error("获取用户角色失败", err)
          })
        }
      }
    }
)

const emits = defineEmits(['update:modelValue', 'initUserList'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await requestUtil.post("system/user/grant_role/", {"id": form.value.id, "roleIds": form.value.checkedRoles})
      .then(res => {
        try {
          ElMessage.success("执行成功！")
          emits("initUserList")
          handleClose();
        } catch (error) {
          ElMessage.error("执行失败！")
        }
      })
    } else {
      ElMessage.error("表单验证失败！")
    }
  })
}
</script>

<style scoped>

</style>
